﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Security;
using JCSoft.Collect.Bussness;

namespace JCSoft.Collect
{
    public class WebUtility
    {
        public static void SetAuthCookie(HttpContextBase context, User user)
        {
            FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(
                    1,
                    user.UserName,
                    DateTime.Now,
                    DateTime.Now.AddMinutes(30),
                    true,
                    user.UserName + "|" + user.UserID.ToString());

            var hash = FormsAuthentication.Encrypt(ticket);
            var cookie = FormsAuthentication.GetAuthCookie(FormsAuthentication.FormsCookieName, true);
            cookie.Value = hash;
            cookie.Name = FormsAuthentication.FormsCookieName;

            context.Response.Cookies.Add(cookie);
        }

        private const string MIDDLE_TIER_KEY = "JCSoft_Collect_MT";
        public static MiddleTier GetMiddleTier()
        {
            HttpContextBase context = new HttpContextWrapper(System.Web.HttpContext.Current);

            if (context == null)
            {
                throw new ArgumentNullException("context");
            }

            MiddleTier mt = (MiddleTier)context.Application[MIDDLE_TIER_KEY];

            if (mt == null)
            {
                context.Application.Lock();
                mt = (MiddleTier)context.Application[MIDDLE_TIER_KEY];

                if (mt == null)
                {
                    mt = MiddleTier.Instance;
                    context.Application.Add(MIDDLE_TIER_KEY, mt);
                }

                context.Application.UnLock();
            }

            return mt;
        }
    }
}
